package org.csu.zhangdian.controller;

import org.csu.zhangdian.domain.Account;
import org.csu.zhangdian.domain.Store;
import org.csu.zhangdian.service.AccountService;
import org.csu.zhangdian.service.StoreService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/Home/")
@SessionAttributes({"account"})
public class AccountController {

    @Autowired
    private AccountService accountService;

    @Autowired
    private StoreService storeService;

    @GetMapping("login")
    public String login(){
        return "index";
    }

    @PostMapping("signon")
    public String signon(String username, String password, Model model, HttpSession session) {
        Account account = accountService.getAccount(username, password);

        if (account == null) {
            String msg = "用户名或密码错误，请重新输入";
            model.addAttribute("msg", msg);
            return "index";
        } else {
            account.setPassword(null);
            model.addAttribute("account", account);
            session.setAttribute("account",account);
            return "home/home";

        }
    }

    //账号信息
    @RequestMapping("info")
    public String info(Model model, HttpServletRequest request){
        HttpSession session1 = request.getSession();
        Account account = (Account) session1.getAttribute("account");
        Store store = storeService.getSA(account.getUsername());
        model.addAttribute("address", store.getAddress());
        model.addAttribute("storeName",store.getStoreName());
        model.addAttribute("username",store.getUsername());
        model.addAttribute("duty",store.getDuty());

        return "/Information/info";
    }

    //账号管理
    @GetMapping("editPasswordForm")
    public String editPasswordForm() {
        return "Information/password";
    }

    //修改密码
    @PostMapping("editPassword")
    public String editPassword(Account account, String repeatedPassword, Model model) {
        if (account.getPassword() == null || account.getPassword().length() == 0 || repeatedPassword == null || repeatedPassword.length() == 0) {
            String msg = "密码不能为空！";
            model.addAttribute("msg", msg);
           // return "Information/password";
        } else if (!account.getPassword().equals(repeatedPassword)) {
            String msg = "两次密码不一致！";
            model.addAttribute("msg", msg);
            //return "Information/password";
        } else {
            accountService.updatePassword(account);
            account = accountService.getAccount(account.getUsername());
            model.addAttribute("account", account);
            String msg = "修改成功！";
            model.addAttribute("msg", msg);
        }
        return "Information/password";
    }


}
